/**
 * 
 */
package com.fox.webapp.persistent.impl;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.util.StringUtils;

import com.fox.webapp.domain.Policy;
import com.fox.webapp.persistent.custom.PolicyRepositoryCustom;

/**
 * @author yockii
 *
 */
public class PolicyRepositoryImpl implements PolicyRepositoryCustom {
	
	@Autowired
	private MongoTemplate mongoTemplate;
	
	/* (non-Javadoc)
	 * @see com.fox.webapp.persistent.custom.PolicyRepositoryCustom#updatePolicy(com.fox.webapp.domain.Policy)
	 */
	@Override
	public Policy updatePolicy(Policy policy) {
		Query query = new Query(where("id").is(policy.getId()));
		Update update = new Update();
		if(StringUtils.hasText(policy.getPolicyContent())){
			update.set("policyContent", policy.getPolicyContent());
		}
		if(policy.getStartTime() != null){
			update.set("updateTime", policy.getStartTime());
		}
		if(policy.getEndTime() != null){
			update.set("endTime", policy.getEndTime());
		}
		if(policy.getBroker() != null){
			update.set("broker", policy.getBroker());
		}
		return mongoTemplate.findAndModify(query, update, FindAndModifyOptions.options().returnNew(true), Policy.class);
	}

}
